package com.hongkuncheng.cms.controller.admin;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

import org.hibernate.Criteria;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.OrderForSql;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.AdminGlobalpermission;
import com.hongkuncheng.cms.model.AdminRole;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.Department;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 绩效统计
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/articlestat")
public class AarticlestatController extends BaseController {

    // 按用户统计
    @RequestMapping("byadmin")
    public String byadmin() {
        checkAdminPermission("office_articlestat_byadmin");
        Criteria criterAdmin = factorySession.createCriteria(Admin.class, "this_")
                .createAlias("adminReAdminRoles", "arac", JoinType.LEFT_OUTER_JOIN)
                .createAlias("arac.adminRole", "admin_adminrole", JoinType.LEFT_OUTER_JOIN);
        StringBuilder callbackparams = new StringBuilder();
        int departmentId = request.getParameter("departmentid") == null ? 0 :
                Integer.parseInt(request.getParameter("departmentid"));
        if (departmentId > 0) {
            criterAdmin.add(Restrictions.eq("department.id", departmentId));
            callbackparams.append("&departmentid=" + departmentId);
        }
        request.setAttribute("departmentid", departmentId);
        int adminroleId = request.getParameter("adminroleid") == null ? 0 :
                Integer.parseInt(request.getParameter("adminroleid"));
        if (adminroleId > 0) {
            criterAdmin.add(Restrictions.eq("admin_adminrole.id", adminroleId));
            callbackparams.append("&adminroleid=" + adminroleId);
        }
        request.setAttribute("adminroleid", adminroleId);
        int adminglobalpermissionId = request.getParameter("adminglobalpermissionid") == null ? 0 :
                Integer.parseInt(request.getParameter("adminglobalpermissionid"));
        if (adminglobalpermissionId > 0) {
            criterAdmin.add(Restrictions.eq("adminGlobalpermission.id", adminglobalpermissionId));
            callbackparams.append("&adminglobalpermissionid=" + adminglobalpermissionId);
        }
        request.setAttribute("adminglobalpermissionid", adminglobalpermissionId);
        String search = request.getParameter("search") == null ? "" : request.getParameter("search");
        if (!search.isEmpty()) {
            criterAdmin.add(Restrictions.disjunction()
                    .add(Restrictions.like("account", search, MatchMode.ANYWHERE))
                    .add(Restrictions.like("name", search, MatchMode.ANYWHERE))
                    .add(Restrictions.like("position", search, MatchMode.ANYWHERE))
                    .add(Restrictions.like("mobile", search, MatchMode.ANYWHERE))
                    .add(Restrictions.like("email", search, MatchMode.ANYWHERE))
                    .add(Restrictions.like("weixinId", search, MatchMode.ANYWHERE)));
            callbackparams.append("&search=" + search);
        }
        request.setAttribute("search", search);
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<Integer> adminIds = criterAdmin.setProjection(Projections.property("id"))
                .addOrder(Order.asc("sort")).setFirstResult((pageIndex - 1) * datasize)
                .setMaxResults(datasize).list();
        List<Admin> admins = new ArrayList<Admin>();
        if (adminIds.size() > 0) {
            admins = factorySession.createCriteria(Admin.class).add(Restrictions.in("id", adminIds))
                    .list();
            Map<String, int[]> articlecountMaps = new HashMap<String, int[]>();
            for (Admin admin : admins) {
                if (admin.getFace() == null || admin.getFace().isEmpty())
                    admin.setFace("/resource/image/admin/main/defaultface.jpg");
                int[] articlecounts = new int[6];
                for (int i = 0; i < 5; i++) {
                    articlecounts[i] = Integer.parseInt(factorySession.createCriteria(Article.class)
                            .add(Restrictions.eq("admin.id", admin.getId()))
                            .add(Restrictions.eq("articleState.id", i + 1))
                            .setProjection(Projections.count("id")).uniqueResult().toString());
                    articlecounts[5] += articlecounts[i];
                }
                articlecountMaps.put(String.valueOf(admin.getId()), articlecounts);
            }
            request.setAttribute("articlecountMaps", articlecountMaps);
        }
        request.setAttribute("admins", admins);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = admins.size() == 0 ? 0 : Integer.parseInt(criterAdmin
                .setProjection(Projections.countDistinct("id")).setFirstResult(0)
                .uniqueResult().toString());
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        List<Department> departments = factorySession.createCriteria(Department.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("departments", departments);
        List<AdminRole> adminroles = factorySession.createCriteria(AdminRole.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("adminroles", adminroles);
        List<AdminGlobalpermission> adminglobalpermissions = factorySession.createCriteria(AdminGlobalpermission.class)
                .list();
        request.setAttribute("adminglobalpermissions", adminglobalpermissions);
        return view();
    }

    // 按部门统计
    @RequestMapping("bydepartment")
    public String bydepartment() {
        checkAdminPermission("office_articlestat_bydepartment");
        List<Department> departments = factorySession.createCriteria(Department.class)
                .addOrder(OrderForSql.desc("(select count(id) from article where article.admin_id " +
                        "in(select id from admin where admin.department_id=this_.id))")).list();
        Map<String, int[]> articlecountMaps = new HashMap<String, int[]>();
        for (Department department : departments) {
            int[] articlecounts = new int[6];
            for (int i = 0; i < 5; i++) {
                articlecounts[i] = Integer.parseInt(factorySession.createCriteria(Article.class)
                        .createAlias("admin", "admin").createAlias("admin.department", "admin_department")
                        .add(Restrictions.eq("admin_department.id", department.getId()))
                        .add(Restrictions.eq("articleState.id", i + 1))
                        .setProjection(Projections.count("id"))
                        .uniqueResult().toString());
                articlecounts[5] += articlecounts[i];
            }
            articlecountMaps.put(String.valueOf(department.getId()), articlecounts);
        }
        request.setAttribute("articlecountMaps", articlecountMaps);
        request.setAttribute("departments", departments);
        return view();
    }

}
